import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Divider,
  Input,
  Row,
  Select,
  DatePicker,
  Modal,
  Badge,
  Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Item } = Form;
const { Option } = Select;
const { RangePicker } = DatePicker;

type IStatusMapType = 'success' | 'default' | 'warning';
const statusMap = ['', 'success', 'default', 'warning'];
const status = ['', '履约中', '已终止', '草稿'];
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  screen: string;
  loading: boolean;
  hasPath: boolean;
  contractList: any;
}

interface TableListState {
  RescissionDialog: boolean;
  pId: number;
  current: number;
  pageSize: number | undefined;
  formValues: any;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  partnerPosthouseContractList,
  global: { screen, hasPath },
  loading,
}: any) => ({
  contractList: partnerPosthouseContractList,
  screen,
  hasPath,
  loading: loading.effects['partnerPosthouseContractList/fetch'],
}))
class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: '商户名称',
      dataIndex: 'fcs_name',
      width: 150,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowPosthouse(record.id, text)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '合同编号',
      dataIndex: 'contract_num',
      width: 200,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '合同期限',
      dataIndex: 'start_day',
      width: 180,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: (val: IStatusMapType) => <Badge status={statusMap[val]} text={status[val]} />,
    },
    {
      title: '创建人',
      dataIndex: 'create_user',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      width: 140,
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      dataIndex: 'id',
      render: (text: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleShowPosthouse(text, record.fcs_name)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <span
            className={record.status === 1 ? 'operLink' : 'operLinkDisabled'}
            onClick={() => this.handleShowRescissionDialog(text)}
          >
            解约
          </span>
          <Divider type="vertical" />
          <span
            className={record.status === 3 ? 'operLink' : 'operLinkDisabled'}
            onClick={() => this.handleEditPosthouse(text, record.fcs_name)}
          >
            编辑
          </span>
        </div>
      ),
    },
  ];

  state: TableListState = {
    RescissionDialog: false,
    pId: 0,
    current: 1,
    pageSize: 20,
    formValues: {},
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { contractList: { data }, hasPath } = this.props;
    if (data?.list?.length && !hasPath) return;

    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchContractList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchContractList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      formValues: { start_day, end_day, ...others },
    } = this.state;

    if (start_day) {
      others.start_end_day = [moment(start_day), moment(end_day)];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  }

  /**
   * 获取合同列表
   */
  fetchContractList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'partnerPosthouseContractList/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current: pageNum, pageSize: numPerPage } = this.state;
    const params = {
      ...formValues,
      pageNum,
      numPerPage,
    };

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.start_end_day && fieldsValue.start_end_day.length) {
        fieldsValue.start_day = moment(fieldsValue.start_end_day[0]).format('YYYY-MM-DD');
        fieldsValue.end_day = moment(fieldsValue.start_end_day[1]).format('YYYY-MM-DD');
      } else {
        fieldsValue.start_day = '';
        fieldsValue.end_day = '';
      }
      delete fieldsValue.start_end_day;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '驿站合同',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleFormReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站合同',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 添加合同
   */
  handleAddPosthouse = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '添加驿站合同',
      url: '/partner/posthouseContract/list/add',
    });
  };

  /**
   * 编辑合同
   */
  handleEditPosthouse = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/partner/posthouseContract/list/edit/${id}`,
    });
  };

  /**
   * 查看合同
   */
  handleShowPosthouse = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/partner/posthouseContract/list/detail/${id}`,
    });
  };

  /**
   * 打开解约提示框
   */
  handleShowRescissionDialog = (pId: number) => this.setState({ pId, RescissionDialog: true });

  /**
   * 确定解约提示框
   */
  handleConfirmRescission = () => {
    this.handleHideRescissionDialog();
    const { pId: id } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'partnerPosthouseContractList/Rescission',
      payload: { ...this.getQueryParams(), id },
    });
  };

  /**
   * 关闭解约提示框
   */
  handleHideRescissionDialog = () => this.setState({ RescissionDialog: false });

  /**
   * 分页
   */
  onSelectChange = (page: number, psize: number | undefined) => {
    const { formValues } = this.state;
    const query = { ...formValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站合同',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem() {
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <Item label="合同期限" colon={false}>
              {getFieldDecorator('start_end_day')(
                <RangePicker
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD"
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="商户名称" colon={false}>
              {getFieldDecorator('franchisee_name')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="合同状态" colon={false}>
              {getFieldDecorator('status')(
                <Select placeholder="不限" allowClear>
                  <Option value="1">履约中</Option>
                  <Option value="2">已终止</Option>
                  <Option value="3">草稿</Option>
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="合同编号" colon={false}>
              {getFieldDecorator('contract_num')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button type="primary" htmlType="submit" className="smallButton">
                查询
              </Button>
              <Button
                className="addButton smallButton marginL16"
                type="primary"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      pageSize,
      current,
      RescissionDialog,
    } = this.state;

    const {
      contractList: { data },
      screen,
      loading,
    } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
        showQuickJumper: true,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              onClick={this.handleAddPosthouse}
            >
              &nbsp;添加&nbsp;
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            loading={loading}
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
        <Modal
          title="确认提示"
          style={{ top: 200 }}
          visible={RescissionDialog}
          onOk={this.handleConfirmRescission}
          onCancel={this.handleHideRescissionDialog}
        >
          <p>您确定要终止此合同吗？</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
